iT邦幫忙

1

【前端動手玩創意】置頂按鈕,老梗經典|帶你的網頁搭電梯(12)

  • 分享至 

  • xImage
  •  

目錄

【前端動手玩創意】等待的轉圈圈效果 (1)
【前端動手玩創意】google五星評分的星星(2)
【前端動手玩創意】CSS-3D卡片翻轉效果(3) (今天難度頗高,想挑戰再進來!)
【前端動手玩創意】一句CSS做出好看的hero section!(4)
【前端動手玩創意】創造一個Skill bar(5)
【前端動手玩創意】遮蔽廣告(D卡未登入)腳本、自定義新增名單(6)
【前端動手玩創意】前端canvas截圖的招式!竟然有三招,可存成SVG或PNG (7)
【前端動手玩創意】讓你的PDF檔案更難被抓取(8)
【前端動手玩創意】哇操!你敢信?花式寫todo-list,body裡面一行都沒有也能搞?(9)
【前端動手玩創意】卡片製作,才不是!是卡片製作器!(10)

前情提要

每個人寫網頁都一定會有一些重複的老梗,就算是2023年了,也躲不掉的那種。
放心,我說的不是nav-bar這種東西,
而是稍微又更有趣一點的小工具,也就是每個人回家都幾乎要經歷的一個小空間:「電梯」

沒錯!就是擁有電梯效果的置頂按鈕!

點下去就能夠跳到網頁的最上面,就像是我們回家的電梯,對吧?

置頂按鈕效果(back to the top button)

原理解說

其實只是做出一個fixed的按鈕,然後使用JS設定,藉由scrollTop的API就可以達成了!

程式碼內容

html的部分

<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>

CSS的部分

#myBtn {
  display: none; /* Hidden by default */
  position: fixed; /* Fixed/sticky position */
  bottom: 20px; /* Place the button at the bottom of the page */
  right: 30px; /* Place the button 30px from the right */
  z-index: 99; /* Make sure it does not overlap */
  border: none; /* Remove borders */
  outline: none; /* Remove outline */
  background-color: red; /* Set a background color */
  color: white; /* Text color */
  cursor: pointer; /* Add a mouse pointer on hover */
  padding: 15px; /* Some padding */
  border-radius: 10px; /* Rounded corners */
  font-size: 18px; /* Increase font size */
}

#myBtn:hover {
  background-color: #555; /* Add a dark-grey background on hover */
}

JS部分

// Get the button:
let mybutton = document.getElementById("myBtn");

// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    mybutton.style.display = "block";
  } else {
    mybutton.style.display = "none";
  }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0; // For Safari
  document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}

心得後記

今天玩的是很基礎的東西,雖然老梗,但是經典。
經典就是無法避免,因此就算拿來練習也不為過,所謂的進階也只是基礎的招數重覆與變化。
就像愛因斯坦說:專家是訓練有素的狗。
也像是李小龍說的:不怕練一萬招,只怕一招練一萬次。

我們不需要把太簡單的東西視為無聊,可以用另一種心態去面對,
就彷彿蜘蛛人穿越新宇宙,另一個世界的自己,也許是另一種新的境界與心境。
學會去面對、接受,就是成長的開始!(๑•ั็ω•็ั๑)


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
f88083
iT邦新手 5 級 ‧ 2023-07-14 04:03:11

感謝分享👍

我要留言

立即登入留言